<div id='odds-container'>
<style type="text/css">
table td { 
	padding:8px; 
}
</style>


<!-- This is only shown if the site is not active -->
<div id='enable' style='display:none'>
    <a href="javascript:void(0)">Enable stacked odds for this site</a>

    <div class='update-information' style='display:none'> <!-- this is displayed when the button is clicked -->

        <p>Retrieving the data may take some time depending on the speed of your internet connection. Do not close the current page until setup has completed</p>

        <table>
            <tr>
                <td>Setup Stage: </td>
                <td class='setup-stage'>0</td>
            </tr>
            <tr>
                <td>Downloading Tags</td>
                <td class='download-tag-count'>0</td>
            </tr>
            <tr>
                <td>Downloading Answers</td>
                <td class='download-answer-count'>0</td>
            </tr>
            <tr>
                <td>Downloading Questions</td>
                <td class='download-question-count'>0</td>
            </tr>
        </table>
        <span class='error supernova'></span>

    </div>
</div>

<!-- This is only shown if the site is active -->
<div id='manage' style='display:none'>

    <p>
        <div id="setup" style="display:none;color:green">
            Stacked Odds is now setup!. Make sure to add tags that you are interested using the box below.
        </div>
        <script>
        require(['lib/hashstring'], function(Hashstring){
            if ( Hashstring.contains('justsetup') ){
                $('#manage #setup').show();
            }
        });
        </script>
    </p>

    <h3>Inference Engine</h3>
    <p>
        The inference engine is the code that does the calculations to try and infer what questions you can answer.Ideally there should be a set of possible engines to chose from but due to time constrains there is only one.
    </p>
    <p>
        Enter a set of tags you are interested in. These should just be the tags that always occur in the questions tags. For example if you were mainly interested in answering C++ and PHP questions you would enter "c++ php". These are used as a hint to the engine <br />

        <!--list of tags -->
        <div id="inference-tag-list">
        </div>

        <!-- Use the se tag bar so that we get auto complete -->
        <input id="inference-tags" name="inference-tags" type="text" size="20" value="" class="edit-field-overlayed ac_input" autocomplete="off">
        <input type="submit" value="Add" id='inference-tag-add' /><br />
        Enabled <input type="checkbox" id="inference-enabled"><br />
    </p>
   <script>
   //this is the script for the tag guessing
   $.getScript('http://sstatic.net/Js/tageditor.js?v=8f2c6ce6e6b9', function(){
        bindTagFilterAutoComplete('#inference-tags');
   });
    </script>
    <script>
        //displays the current list of tags 
        function displayTagList(){
            $('#inference-tag-list').html('');
            var tagString = localStorage.getItem('inference.tags') ;
            if ( tagString != null && tagString.length ){
                var tags = tagString.split(' ');
                tags.forEach(function(t){
                    $('#inference-tag-list').append('<a href="/questions/tagged/'+t+'" class="post-tag" rel="tag">'+t+'</a>')
                                            .append('<span class="delete-tag" title="remove this tag"></span>');
                });
                $('#inference-tag-list .delete-tag').unbind().hover(function(){
                    $(this).attr('class', 'delete-tag-hover')
                },function(){
                    $(this).attr('class', 'delete-tag')
                }).click(function(){
                    //when it is removed, we just refresh the tag list as it is easier
                    //than fiddling around working out which one to remove
                    tags.splice(tags.indexOf($(this).html()), 1);
                    localStorage.setItem('inference.tags', tags.join(' ')) ;
                    displayTagList();
                });
            }

        }
        displayTagList();

        //function to update the tag list when something changes
        $('#inference-tag-add').click(function(){
            var tagString = localStorage.getItem('inference.tags') 
            if ( tagString == null ){
                tagString = '';
            }

            var val = $('#inference-tags').attr('value');
            if ( tagString.split(' ').indexOf(val) == -1 ){
                tagString += ' ' + val;
                localStorage.setItem('inference.tags', $.trim(tagString)) ;
            }
            $('#inference-tags').attr('value', '');
            displayTagList();

        })
        
    </script>

    <script>
    //the infernace enabled check box
        if ( localStorage.getItem('inference.enabled') != null ){
            var state = localStorage.getItem('inference.enabled') == 'true' ? 1 : 0;
            $('#inference-enabled').attr('checked', state) ;
        }else{
            $('#inference-enabled').attr('checked', 1);
        }
        $('#inference-enabled').change(function(){
            localStorage.setItem('inference.enabled', $('#inference-enabled').attr('checked'))
        });
    </script>

    
    <h3>Filters</h3>
    <p>
        Filters allow you to filter out some questions based on data other than if the inference engine thinks you
        can answer it. These could include a users accept rate, reputation or some other metric. 
    </p>

    <p>
        <form id='filters'>
            <table> 
                <tr>
                    <td></td>
                    <td></td>
                    <td>Enabled</td>
                </tr>
                <tr class='acceptratio' style="text-align:center">
                    <td>Accept rate greater than</td>
                    <td><input class='rate' type="text" style="width:3em" /> (percent)</td>
                    <td><input class='enabled' type="checkbox"></td>
                </tr>
                <!--
                <tr>
                    <td>Vote:Question ratio greater than</td>
                    <td><input type="text" /></td>
                    <td><input type="checkbox"></td>
                </tr>
                -->
            </table>
        </form>
    </p>
    <script>
    (function(){
        var enabledElem = $('#filters .acceptratio .enabled');
        var rateElem = $('#filters .acceptratio .rate');
        var enabled = localStorage.getItem('filter.acceptratio.enabled');
        if ( enabled != null ){
            var state = enabled == 'true' ? 1 : 0;
            enabledElem.attr('checked', state) ;
        }else{
            rateElem.attr('checked', 0);
        }
        var rate = localStorage.getItem('filter.acceptratio.rate');
        if ( rate != null ){
            rateElem.attr('value', rate) ;
        }else{
            rateElem.attr('value', 50) ;
        }

        var saveFunc = function(){
            localStorage.setItem('filter.acceptratio.enabled', enabledElem.attr('checked'));
            localStorage.setItem('filter.acceptratio.rate', rateElem.attr('value'));
        };
        $('#filters .acceptratio .enabled').change(saveFunc);
        $('#filters .acceptratio .rate').change(saveFunc);
    })();
    </script>


    <h3>Update Details</h3>
    <a href="javascript:void(0)">Update stacked odds data</a>
    <p>
        If you have written significantly more answers, then you may need to update the stacked odds database
        to reflect the new data. This may take some time.
    </p>

    <div class='update-information' style='display:none'> <!-- this is displayed when the button is clicked -->

        <p>Retrieving the data may take some time depending on the speed of your internet connection. Do not close the current page while until this has completed</p>

        <table class='update-details' >
            <tr>
                <td>Setup Stage: </td>
                <td class='setup-stage'>0</td>
            </tr>
            <tr>
                <td>Downloading Tags</td>
                <td class='download-tag-count'>0</td>
            </tr>
            <tr>
                <td>Downloading Answers</td>
                <td class='download-answer-count'>0</td>
            </tr>
            <tr>
                <td>Downloading Questions</td>
                <td class='download-question-count'>0</td>
            </tr>
        </table>
        <span class='error supernova'></span>
    </div>

</div>

<script>

/**
 * Decides what we need to show depending on if the site has been setup
 */
require(['config', 'pages', 'lib/hashstring', 'db', 'db/sites', 'lib/jquery'],
function(Config, Page, Hashstring, Db, Sites){
    if ( SiteInformation.IsActive == 1 ){
        $('#manage').show();
    }else{
        $('#enable').show();
    }
});
</script>

<script>
/**
 * Deals with what happens when the user presses the button to enable stacked odds for this site
 */
require(['config', 'contentscript', 'pages/user/options', 'lib/hashstring', 'chain','se/site', 'se/api', 'db', 'db/sites', 'lib/jquery'],
function(Config, ContentScript, Helper, Hashstring, Chain, Site, Api,Db, Sites){
    function addDataCreationHandler(id, doneFunc){ //todo func name
        $('#'+id+' a').click(function(){

        //increases the stage value
        var incStage = function(){
            var e = $('#' + id + ' .setup-stage');
            e.html(parseInt(e.html()) + 1);
        };
        ///turns the stage green
        var setStageDone = function(){
            $('#' + id + ' .setup-stage').attr('style', 'color:green');
        };
        ///Increments the number in a table cell
        var incCount = function(type){
            var e = $('#' + id + ' .download-' + type + '-count');
            e.html(parseInt(e.html()) + 1);
        }
        ///sets the text in a cell green
        var setDone = function(type){
            $('#' + id + ' .download-' + type + '-count').attr('style', 'color:green');
        }

        var setStarted = function(type){
            $('#' + id + ' .download-' + type + '-count').attr('style', 'color:#C35617');
        }

        /**
         * runs a helper function on a database
         *
         * unlike other functions with callbacks, this requires both a 
         * success and error property on the callback object
         */
        var setupDb = function(func, args, name, callbacks){
            setStarted(name);
            args.push({
                step:function(){ incCount(name); },
                error:callbacks.error,
                done:function(){
                    setDone(name);
                    incStage();
                    callbacks.success();
                }
            })
            func.apply(null, args);
        }
        
        //The code that does the work
        $('#' + id + ' .update-information').show();

        var api = new Api.Api(SiteInformation.ApiUrl, Config.ApiKey);
        var uid = SiteInformation.UserId;

        incStage();
        Chain.create()
             .queue(Helper.destroyDatabases, [api], 'success') //removes all data from the databases
             .queue(Helper.createDatabases, [api], 'success') //creates the databases
             .queue(setupDb, [Helper.getTagInformation, [api], 'tag'], 'success') //gets tag data
             .queue(setupDb, [Helper.getAnswerInformation, [api, uid], 'answer'], 'success') //answer data
             .queue(setupDb, [Helper.getQuestionInformation, [api, Config.DefaultSampleSize], 'question'], 'success') 
             .success(
                function(){
                    incStage();

                    ContentScript.sendMessage('setSiteActive', window.location.host, function(){
                           incStage();
                           setStageDone();
                           doneFunc && doneFunc();
                    });
                })
             .error(
                function(msg){
                    $('#' + id + ' .error').text(msg);
                })
             .exec();
    });
    }
    addDataCreationHandler('enable', function(){
       Hashstring.set('justsetup','1');
       window.location.reload();
    });
    $('#enable').click(function(){
        $('#enable a').hide();
    });

    addDataCreationHandler('manage');
});


</script>


</div>
